<div>
    <div id="toolbar"><h2 class="no-margin">Users Management</h2></div>
    <table id="table"></table>
</div>

<script>
    function userLevelfilter() {
        var temp = ["All"];
        for (var i = 1; i < userinfo.userLevels.length; i++)
            temp.push(userinfo.userLevels[i]);
        console.log(temp);
        return temp;
    }

    function Rolefilter() {
        var temp = [{
            "text": "All",
            "id": "-",
            "element": "HTMLOptionElement",
            children: [{"text":"All",id:"-"}]
        }];
        $(userinfo.role).each(function (i, role) {
            var ch = [{ id: "", text: role.roleName }];
            var id = [];
            $(role.roleChilds).each(function (index, child) {
                id.push(child.roleChildId);
                ch.push({ id: child.roleChildId, text: role.roleName + " " +  child.roleChildName });
            });
            ch[0].id = id.join("-");
            temp.push({
                text: role.roleName,
                id: "group-" + id.join("-"),
                "element": "HTMLOptionElement",
                children: ch
            })
        });
        console.log(temp);
        return temp;
    }
    loadTable();

    function loadTable() {
        try {
            if (userinfo == null) throw 'err';
            var options = {
                ajax: function (request) {
                    console.log(request);
                    $.ajax({
                        type: "get",
                        url: apiUrl + "User/Infos",
                        data: request.data,
                        dataType: 'json',
                        success: function (data, status, request) {
                            data.result.total = 10;
                            row = data.result.rows[0]
                            for (var i = 1; i < 20; i++)
                                data.result.rows[i] = row;
                            $('#table').bootstrapTable('load', data.result);
                            $('#table').bootstrapTable('hideLoading');
                        },
                        error: function () {


                        }
                    });
                },

                columns: [{
                    field: "userId",
                    title: "ID",
                    sortable: true,
                    filter: {
                        type: "input"

                    },
                    cardVisible: false,
                    visible: false
                }, {
                    field: "userName",
                    title: "Name",
                    sortable: true,
                    filter: {
                        type: "input"
                    },
                    formatter: clipFormatter,
                }, {
                    field: "userNick",
                    title: "Nick",
                    sortable: true,
                    filter: {
                        type: "input"
                    },
                    formatter: clipFormatter,
                }, {
                    field: "userPhone",
                    title: "Phone",
                    filter: {
                        type: "input"

                    },
                    sortable: true,
                    editable: false,
                    formatter: clipFormatter,
                }, {
                    field: "userEmail",
                    title: "Email",
                    filter: {
                        type: "input"
                    },
                    sortable: true,
                    cardVisible: true,
                    visible: true,
                    formatter: clipFormatter,
                }, {
                    field: "userLevel",
                    title: "Level",
                    filter: {
                        type: "select",
                        data: userLevelfilter(),
                    },
                    cardVisible: true,
                    sortable: true,
                    visible: true,
                    editable: {
                        type: 'select',
                        title: 'Level',
                        source: function () { var temp = []; for (var i = 1; i < userinfo.userLevels.length; i++)temp.push({ value: i, text: userinfo.userLevels[i] }); return temp; }
                    },
                    //formatter:levelFormatter
                }, {
                    field: "password",
                    title: "Password",
                    filter: {
                        type: "input"
                    },
                    cardVisible: false,
                    sortable: false,
                    visible: true,
                    formatter: passwordFormatter,
                }, {
                    field: "roleChildId",
                    title: "Role",
                    filter: {
                        type: "select",
                        multiple: true,
                        allowClear:true,
                        data: Rolefilter(),
                    },
                    editable: {
                        type: 'select',
                        title: 'Role',
                        source: function () {
                            var temp = [];
                            //debugger;
                            $(userinfo.role).each(function (i,role) {
                                $(role.roleChilds).each(function (index,child) {
                                    temp.push({
                                        value: child.roleChildId, text: role.roleName + " " + child.roleChildName
                                    });
                                });
                            });
                            return temp;
                        }
                    },
                    sortable: true,
                }],
                height: $(window).height()-100,
                filter: true,
                pagination: true,
                showColumns: true,
                striped: true,
                pageSize: 15,
                sidePagination: "server",
                paginationDetailHAlign: "left",
                paginationHAlign: "right",
                smartDisplay: true,
                showFullscreen: true,
                pageList: [5, 10, 15, 20, 30, 50, "ALL"],
                clickToSelect: false,
                showRefresh: true,
                showToggle: true,
                showExport: true,
                showMultiSort: true,
                sortPriority:[{ "sortName": "userId", "sortOrder": "asc" }],
                toolbar: "#toolbar",
                responseHandler: function (res) {
                    console.log(res);

                    return res;
                },
                onClickCell: ClickCell,
                onEditableSave: function (field, row, oldValue, $el) {
                    if (field == "userLevel") {
                        $.ajax({
                            type: "post",
                            url: apiUrl + "/User/SetUserLevel",
                            data: { UserId: row.userId, UserLevel: userinfo.userLevels[row.userLevel] },
                            dataType: 'JSON',
                            success: function (data) {
                                if (data.status.code == 0) {
                                    //swal("已保存", "", "success");
                                    $(".editable-unsaved").removeClass("editable-unsaved");
                                    $.smallBox({
                                        title: "Success",
                                        content: "<i class='fa fa-clock-o'></i> <i></i>Data had been updated",
                                        color: "#659265",
                                        iconSmall: "fa fa-check fa-2x fadeInRight animated",
                                        timeout: 8000
                                    });
                                }
                            },
                            error: function () {
                                alert("网络异常或失败");
                            }
                        });
                    }
                }
            };
            if ($(window).width() < 400) {
                options.cardView = true;
                options.pageSize = 3;
            } else {

            }
            $("#table").bootstrapTable(options)
            setTimeout(function () {
                //$('.fixed-table-container').css("max-height", "" + ($(window).height() - $('.fixed-table-container').position().top - 100) + "px")
                //$('.fixed-table-container').css("overflow-y", "auto")
                $(".fixed-table-toolbar").addClass("panel-heading");
            }, 1000);
        }
        catch (e) {
            setTimeout(function () {
                loadTable();
            }, 1000);
            console.log(e);
        }
    }

    function timeFormatter(value, row, index) {
        var res = '';
        if (value == 0) {
            res = '不存在记录';
        } else {
            if (Date.parse(new Date()) / 1000 - value < 60) {
                res = "1分钟内";
            } else {
                if (Date.parse(new Date()) / 1000 - value < 3600) {
                    res = Math.round((Date.parse(new Date()) / 1000 - value) / 60) + "分钟前";
                } else {
                    if (new Date(new Date().setHours(0, 0, 0, 0)) / 1000 < value) {
                        res = new Date(value * 1000).format("hh:mm");
                    } else {
                        res = new Date(value * 1000).format("yy-MM-dd hh:mm");
                    }
                }
            }

        }
        return res;
    }

    function passwordFormatter(value, row, index) {
        return '<a herf="javascript:void(0)">Reset</a>';
    }

    function clipFormatter(value, row, index) {
        if (value == null) return null;
        return '<span class="needCopy" data-clipboard-text="' + value + '"><a>' + value + '</a> <i class="fa fa-copy "></i>';
    }

    function ClickCell(field, value, row, $element) {
        if (field == 'password') {
            var rowtemp = row;
            $.SmartMessageBox({
                title: 'Are you sure you want to reset [' + row['userNick'] + "'s] password?",
                content: "The password will be reset to 123456 and will be asked to reset the password the next time logs in.",
                buttons: '[Reset][Cancel]'
            }, function (ButtonPressed) {
                if (ButtonPressed === "Reset") {
                    console.log(rowtemp);
                    $.ajax({
                        type: "post",
                        url: apiUrl + "User/ResetPassword",
                        data: {userId:row.userId},
                        dataType: 'JSON',
                        success: function (data, status) {
                            if (data.status.code == 0) {
                                $.smallBox({
                                    title: "Password has been reset",
                                    content: "<i class='fa fa-clock-o'></i> <i>The password reset to 123456 and will be asked to reset the password the next time logs in.</i>",
                                    color: "#659265",
                                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
                                    timeout: 8000
                                });
                            } else {
                                alert(data.status.msg);
                            }
                        },
                        error: function () {
                            alert("Error! Check network!");

                        }
                    })
                    //lineInfo.lStation.splice(tempStations, 1);
                    //reloadLine();

                }
                //tempStations = null;
            });
        }
    }
</script>
